<template>
  <div class="club-applications-container">
    <div class="section-header">
      <h2>申请管理</h2>
      <div class="tab-container">
        <el-radio-group v-model="applicationType" size="medium">
          <el-radio-button label="join">加入申请</el-radio-button>
          <el-radio-button label="exit">退出申请</el-radio-button>
        </el-radio-group>
      </div>
    </div>

    <!-- 加入申请列表 -->
    <div v-if="applicationType === 'join'">
      <div class="status-filter">
        <el-select v-model="statusFilter" placeholder="状态筛选" clearable @change="filterApplications">
          <el-option label="全部状态" value=""></el-option>
          <el-option label="待处理" value="pending"></el-option>
          <el-option label="已通过" value="approved"></el-option>
          <el-option label="已拒绝" value="rejected"></el-option>
        </el-select>
      </div>

      <el-table
        :data="filteredApplications"
        style="width: 100%"
        stripe
        :header-cell-style="{ backgroundColor: '#1f1b24', color: '#ffffff' }"
        :cell-style="{ backgroundColor: '#28232e', color: '#b0bec5' }"
        v-loading="loading"
      >
        <!-- <el-table-column label="头像" width="80">
          <template #default="scope">
            <img
              :src="scope.row.avatar || '../../components/icons/touxiang.png'"
              alt="用户头像"
              style="width: 40px; height: 40px; border-radius: 50%;"
            >
          </template>
        </el-table-column> -->
        <el-table-column prop="applyTime" label="申请时间" min-width="160">
          <template #default="scope">
            {{ formatDate(scope.row.applyTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" min-width="120"></el-table-column>
        <el-table-column prop="name" label="真实姓名" min-width="100"></el-table-column>
        <el-table-column prop="gender" label="性别" min-width="60"></el-table-column>
        <el-table-column prop="studentId" label="学号" min-width="140"></el-table-column>
        <el-table-column prop="college" label="学院" min-width="150"></el-table-column>
        <el-table-column prop="className" label="班级" min-width="120"></el-table-column>
        <el-table-column prop="hobbies" label="兴趣爱好" min-width="150"></el-table-column>
        <el-table-column prop="reason" label="申请理由" min-width="200"></el-table-column>
        <el-table-column prop="status" label="状态" min-width="90">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <div v-if="scope.row.status === 'pending'">
              <el-button
                size="small"
                type="success"
                @click="approveApplication(scope.row, 'join')"
              >通过</el-button>
              <el-button
                size="small"
                type="danger"
                @click="rejectApplication(scope.row, 'join')"
              >拒绝</el-button>
              <el-button
                size="small"
                type="primary"
                @click="viewApplicationDetail(scope.row)"
              >详情</el-button>
            </div>
            <div v-else>
              <el-button
                size="small"
                type="primary"
                @click="viewApplicationDetail(scope.row)"
              >详情</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 退出申请列表 -->
    <div v-if="applicationType === 'exit'">
      <div class="status-filter">
        <el-select v-model="statusFilter" placeholder="状态筛选" clearable @change="filterApplications">
          <el-option label="全部状态" value=""></el-option>
          <el-option label="待处理" value="pending"></el-option>
          <el-option label="已通过" value="approved"></el-option>
          <el-option label="已拒绝" value="rejected"></el-option>
        </el-select>
      </div>

      <el-table
        :data="filteredApplications"
        style="width: 100%"
        stripe
        :header-cell-style="{ backgroundColor: '#1f1b24', color: '#ffffff' }"
        :cell-style="{ backgroundColor: '#28232e', color: '#b0bec5' }"
        v-loading="loading"
      >
        <el-table-column label="头像" min-width="80">
          <template #default="scope">
            <img
              :src="scope.row.avatar || '../../components/icons/touxiang.png'"
              alt="用户头像"
              style="width: 40px; height: 40px; border-radius: 50%;"
            >
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" min-width="120"></el-table-column>
        <el-table-column prop="applyTime" label="申请时间" min-width="160">
          <template #default="scope">
            {{ formatDate(scope.row.applyTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="reason" label="退出原因" min-width="200"></el-table-column>
        <el-table-column prop="status" label="状态" min-width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <div v-if="scope.row.status === 'pending'">
              <el-button
                size="small"
                type="success"
                @click="approveApplication(scope.row, 'exit')"
              >通过</el-button>
              <el-button
                size="small"
                type="danger"
                @click="rejectApplication(scope.row, 'exit')"
              >拒绝</el-button>
            </div>
            <span v-else>已处理</span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next"
        :total="totalItems"
        background
      ></el-pagination>
    </div>

    <!-- 拒绝申请对话框 -->
    <el-dialog
      :title="rejectDialogTitle"
      v-model="showRejectDialog"
      width="40%"
      :custom-class="'dark-dialog'"
    >
      <p>您正在拒绝 <strong>{{ selectedApplication?.username }}</strong> 的申请。</p>
      <p>请输入拒绝原因：</p>
      <el-input
        v-model="rejectReason"
        type="textarea"
        rows="3"
        placeholder="请输入拒绝原因（选填）"
      ></el-input>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showRejectDialog = false">取消</el-button>
          <el-button type="danger" @click="confirmReject">确认拒绝</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 申请详情对话框 -->
    <el-dialog
      title="申请详情"
      v-model="showDetailDialog"
      width="50%"
      :custom-class="'dark-dialog'"
    >
      <div v-if="selectedApplication" class="application-detail">
        <div class="applicant-header">
          <div class="applicant-avatar">
            <img :src="selectedApplication.avatar || '../../components/icons/touxiang.png'" alt="用户头像">
          </div>
          <div class="applicant-info">
            <h3>{{ selectedApplication.name }} ({{ selectedApplication.username }})</h3>
            <p>
              <el-tag :type="getStatusType(selectedApplication.status)">
                {{ getStatusText(selectedApplication.status) }}
              </el-tag>
              <span class="apply-time">申请时间: {{ formatDate(selectedApplication.applyTime) }}</span>
            </p>
          </div>
        </div>

        <el-divider></el-divider>

        <div class="detail-item">
          <span class="label">学号:</span>
          <span class="value">{{ selectedApplication.studentId }}</span>
        </div>

        <div class="detail-item">
          <span class="label">学院:</span>
          <span class="value">{{ selectedApplication.college }}</span>
        </div>

        <div class="detail-item">
          <span class="label">班级:</span>
          <span class="value">{{ selectedApplication.className }}</span>
        </div>

        <div class="detail-item">
          <span class="label">性别:</span>
          <span class="value">{{ selectedApplication.gender }}</span>
        </div>

        <div class="detail-item">
          <span class="label">兴趣爱好:</span>
          <span class="value">{{ selectedApplication.hobbies || '未填写' }}</span>
        </div>

        <div class="detail-item">
          <span class="label">申请理由:</span>
          <div class="value reason-text">{{ selectedApplication.reason }}</div>
        </div>

        <template v-if="selectedApplication.status === 'rejected' && selectedApplication.rejectReason">
          <div class="detail-item">
            <span class="label">拒绝原因:</span>
            <div class="value reason-text">{{ selectedApplication.rejectReason }}</div>
          </div>
        </template>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDetailDialog = false">关闭</el-button>
          <template v-if="selectedApplication && selectedApplication.status === 'pending'">
            <el-button type="success" @click="approveFromDetail">通过申请</el-button>
            <el-button type="danger" @click="rejectFromDetail">拒绝申请</el-button>
          </template>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, defineProps } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

// 接收社团ID属性
const props = defineProps({
  clubId: {
    type: [String, Number],
    required: true
  }
})

// 状态变量
const loading = ref(false)
const joinApplications = ref([])
const exitApplications = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const totalItems = ref(0)
const applicationType = ref('join') // 'join' 或 'exit'
const statusFilter = ref('')
const showRejectDialog = ref(false)
const showDetailDialog = ref(false)
const selectedApplication = ref(null)
const rejectReason = ref('')
const applicationTypeText = ref('') // 用于拒绝对话框标题

// 计算当前申请类型的对话框标题
const rejectDialogTitle = computed(() => {
  return applicationTypeText.value === 'join' ? '拒绝加入申请' : '拒绝退出申请'
})

// 根据当前选择的申请类型和筛选条件，返回要显示的申请列表
const filteredApplications = computed(() => {
  let applications = applicationType.value === 'join' ? joinApplications.value : exitApplications.value

  if (statusFilter.value) {
    applications = applications.filter(app => app.status === statusFilter.value)
  }

  return applications
})

// 当申请类型变更时，重置状态筛选
watch(applicationType, () => {
  statusFilter.value = ''
  currentPage.value = 1
  loadApplications()
})

// 获取状态标签类型
const getStatusType = (status) => {
  switch (status) {
    case 'approved': return 'success'
    case 'pending': return 'warning'
    case 'rejected': return 'danger'
    default: return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'approved': return '已通过'
    case 'pending': return '待处理'
    case 'rejected': return '已拒绝'
    default: return '未知'
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';

  try {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  } catch (error) {
    console.error('日期格式化错误:', error);
    return dateString;
  }
};

// 加载申请数据
const loadApplications = async () => {
  loading.value = true
  try {
    console.log('开始加载申请数据，社团ID:', props.clubId, '申请类型:', applicationType.value)

    // 请求加入申请
    if (applicationType.value === 'join') {
      const response = await axios.get(`http://localhost:5000/clubs/${props.clubId}/applications?type=join`);
      console.log('收到加入申请数据:', response.data)
      joinApplications.value = response.data || [];

      // 检查应用数据是否包含_id字段
      if (joinApplications.value.length > 0) {
        joinApplications.value.forEach((app, index) => {
          if (!app._id) {
            console.warn(`警告: 第${index+1}个加入申请缺少_id字段`, app)
          }
        })
      }

      totalItems.value = joinApplications.value.length;
    }
    // 请求退出申请
    else {
      const response = await axios.get(`http://localhost:5000/clubs/${props.clubId}/applications?type=exit`);
      console.log('收到退出申请数据:', response.data)
      exitApplications.value = response.data || [];

      // 检查应用数据是否包含_id字段
      if (exitApplications.value.length > 0) {
        exitApplications.value.forEach((app, index) => {
          if (!app._id) {
            console.warn(`警告: 第${index+1}个退出申请缺少_id字段`, app)
          }
        })
      }

      totalItems.value = exitApplications.value.length;
    }

    console.log('申请数据加载完成')
    loading.value = false;
  } catch (error) {
    console.error('加载申请失败', error)
    if (error.response) {
      console.error('错误响应:', error.response.data)
    }
    ElMessage.error('加载申请失败: ' + (error.response?.data?.message || error.message))
    loading.value = false
  }
}

// 筛选申请
const filterApplications = () => {
  loadApplications()
}

// 分页处理
const handleCurrentChange = (page) => {
  currentPage.value = page
  loadApplications()
}

// 查看申请详情
const viewApplicationDetail = (application) => {
  selectedApplication.value = application
  showDetailDialog.value = true
}

// 从详情页面通过申请
const approveFromDetail = () => {
  if (selectedApplication.value) {
    approveApplication(selectedApplication.value, 'join')
    showDetailDialog.value = false
  }
}

// 从详情页面拒绝申请
const rejectFromDetail = () => {
  if (selectedApplication.value) {
    rejectApplication(selectedApplication.value, 'join')
    showDetailDialog.value = false
  }
}

// 通过申请
const approveApplication = async (application, type) => {
  try {
    console.log('处理申请:', application)
    console.log('申请ID:', application._id)

    if (!application._id) {
      ElMessage.error('申请ID不存在，无法处理')
      return
    }

    // 发送请求更新申请状态
    await axios.put(`http://localhost:5000/clubs/${props.clubId}/applications/${application._id}`, {
      status: 'approved'
    });

    // 更新本地数据
    if (type === 'join') {
      const index = joinApplications.value.findIndex(app => app._id === application._id);
      if (index !== -1) {
        joinApplications.value[index].status = 'approved';
      }
    } else {
      const index = exitApplications.value.findIndex(app => app._id === application._id);
      if (index !== -1) {
        exitApplications.value[index].status = 'approved';
      }
    }

    ElMessage.success(type === 'join' ? '已通过加入申请' : '已通过退出申请');
    // 重新加载数据以获取最新状态
    setTimeout(() => loadApplications(), 500);
  } catch (error) {
    console.error('处理申请失败', error);
    ElMessage.error('处理申请失败: ' + (error.response?.data?.message || error.message));
  }
}

// 拒绝申请（打开对话框）
const rejectApplication = (application, type) => {
  selectedApplication.value = application
  applicationTypeText.value = type
  rejectReason.value = ''
  showRejectDialog.value = true
}

// 确认拒绝
const confirmReject = async () => {
  if (!selectedApplication.value) return

  try {
    console.log('拒绝申请:', selectedApplication.value)
    console.log('申请ID:', selectedApplication.value._id)

    if (!selectedApplication.value._id) {
      ElMessage.error('申请ID不存在，无法处理')
      return
    }

    // 发送请求更新申请状态
    await axios.put(`http://localhost:5000/clubs/${props.clubId}/applications/${selectedApplication.value._id}`, {
      status: 'rejected',
      rejectReason: rejectReason.value
    });

    // 更新本地数据
    if (applicationTypeText.value === 'join') {
      const index = joinApplications.value.findIndex(app => app._id === selectedApplication.value._id);
      if (index !== -1) {
        joinApplications.value[index].status = 'rejected';
        if (rejectReason.value) {
          joinApplications.value[index].rejectReason = rejectReason.value;
        }
      }
    } else {
      const index = exitApplications.value.findIndex(app => app._id === selectedApplication.value._id);
      if (index !== -1) {
        exitApplications.value[index].status = 'rejected';
        if (rejectReason.value) {
          exitApplications.value[index].rejectReason = rejectReason.value;
        }
      }
    }

    ElMessage.success(applicationTypeText.value === 'join' ? '已拒绝加入申请' : '已拒绝退出申请');
    showRejectDialog.value = false;

    // 重新加载数据以获取最新状态
    setTimeout(() => loadApplications(), 500);
  } catch (error) {
    console.error('处理申请失败', error);
    ElMessage.error('处理申请失败: ' + (error.response?.data?.message || error.message));
  }
}

onMounted(() => {
  loadApplications()
})
</script>

<style scoped>
.club-applications-container {
  width: 100%;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h2 {
  margin: 0;
  font-size: 20px;
  color: #ffffff;
}

.tab-container {
  margin-bottom: 20px;
}

.status-filter {
  margin-bottom: 15px;
  display: flex;
  justify-content: flex-end;
}

.status-filter .el-select {
  width: 150px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 申请详情样式 */
.application-detail {
  padding: 10px;
}

.applicant-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.applicant-avatar {
  margin-right: 20px;
}

.applicant-avatar img {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  border: 2px solid rgba(255, 255, 255, 0.1);
}

.applicant-info h3 {
  margin: 0 0 10px 0;
  color: #ffffff;
}

.apply-time {
  margin-left: 15px;
  color: #b0bec5;
  font-size: 14px;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
}

.detail-item .label {
  width: 100px;
  color: #b0bec5;
  flex-shrink: 0;
}

.detail-item .value {
  color: #ffffff;
  flex: 1;
}

.reason-text {
  white-space: pre-line;
  padding: 10px;
  background-color: rgba(255, 255, 255, 0.05);
  border-radius: 4px;
  line-height: 1.5;
}

/* 黑色主题对话框样式 */
:deep(.dark-dialog) {
  background-color: #1f1b24;
  color: #ffffff;
  border: 1px solid #333;
}

:deep(.dark-dialog .el-dialog__header) {
  background-color: #28232e;
  color: #ffffff;
  padding: 15px 20px;
  border-bottom: 1px solid #333;
}

:deep(.dark-dialog .el-dialog__title) {
  color: #ffffff;
}

:deep(.dark-dialog .el-dialog__body) {
  background-color: #1f1b24;
  color: #b0bec5;
  padding: 20px;
}

:deep(.dark-dialog .el-dialog__footer) {
  background-color: #28232e;
  border-top: 1px solid #333;
  padding: 15px 20px;
}

:deep(.dark-dialog .el-input__inner),
:deep(.dark-dialog .el-textarea__inner) {
  background-color: #28232e;
  border: 1px solid #444;
  color: #ffffff;
}

:deep(.dark-dialog .el-input__inner:focus),
:deep(.dark-dialog .el-textarea__inner:focus) {
  border-color: #409EFF;
}
</style>
